/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dropbinserver.controller;

import dropbinserver.helper.Protocol;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author LegACy
 */
public class Responder implements Runnable {
	public Responder() {
		//Initialize
		m_Running		= true;
		m_Connections	= new ArrayList<Socket>();
	}

	public void addConnection(Socket connection) {
		//Add connection to the list
		m_Connections.add(connection);
	}

	public void run() {
		//While running
		while (m_Running) {
			//Sleep for a bit
			try {
				Thread.sleep(50);
			} catch (InterruptedException ex) {}

			//Check for any new connection
			if (!m_Connections.isEmpty()) {
				//Get new connection
				Socket Processed = m_Connections.get(0);
				m_Connections.remove(Processed);

				try {					
					//Send message
					PrintWriter Writer = new PrintWriter(Processed.getOutputStream());
					Writer.println(createResponse(Processed));
					Writer.flush();

					//Close
					Writer.close();
					Processed.close();
				} catch (IOException ex) {}
			}
		}
	}

	protected String createResponse(Socket connection) throws IOException {
		//Variable
		String Result = "";
		
		//Create reader
		BufferedReader Reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

		try {
			//Read conection
			int Action = Reader.read();
			JSONObject Request = new JSONObject(Reader.readLine());

			//Based on action
			Result += (char)(Action + Protocol.RESPONSE_OFFSET);
			switch (Action) {
				case Protocol.ACTION_LOGIN:		Result += processLogin(Request.getString("username"), Request.getString("password"));	break;
				case Protocol.ACTION_LATEST:	Result += processLatest(Request.getString("username"));									break;
				case Protocol.ACTION_STRUCTURE:	Result += processStructure(Request.getString("username"), Request.getInt("version"));	break;
				case Protocol.ACTION_FILE:
					//Initialize path
					String Path = "";
					if (Request.has("path")) {
						//Get path string
						Path = Request.getString("path");
					} else if (Request.has("path-array")) {
						//Get path array
						JSONArray PathArray = Request.getJSONArray("path-array");
						for (int i = 0; i < PathArray.length(); i++) {
							Path += PathArray.getString(i);
							if (i < PathArray.length() - 1) Path += "/";
						}
					} else throw new JSONException("No path element");

					//If done, set result
					Result += processFile(Request.getString("username"), Request.getInt("version"), Path);

					break;
				default:
					Result = "" + (char)0;
			}
		} catch (JSONException ex) {
			Result = "" + (char)Protocol.ACTION_NONE;
		}
		

		//Return result
		return Result;
	}

	protected String processLogin(String username, String password) throws JSONException {
		//Create JSON
		JSONObject Result = new JSONObject();

		//Save data to json
		Result.put("result", true);
		return Result.toString();
	}

	protected String processLatest(String username) throws JSONException {
		//Create JSON
		JSONObject Result = new JSONObject();

		//Save data to json
		Result.put("result", true);
		Result.put("latest", 5);
		return Result.toString();
	}

	protected String processStructure(String username, int version) throws JSONException {
		//Create JSON
		JSONObject Result = new JSONObject();

		//Create structure
		JSONObject Folder1 = new JSONObject();
		Folder1.put("name", "Folder1");
		JSONArray Files1 = new JSONArray();
		Files1.put("File3.txt");
		Files1.put("File4.txt");
		Folder1.put("content", Files1);
		JSONArray Structure = new JSONArray();
		Structure.put("File1.txt");
		Structure.put("File2.txt");
		Structure.put(Folder1);

		//Save data to json
		Result.put("result", true);
		Result.put("structure", Structure);
		return Result.toString();
	}

	protected String processFile(String username, int version, String path) throws JSONException {
		//
		return "";
	}

	protected String processStructureUpload(String username, JSONArray structure) throws JSONException {
		//
		return "";
	}

	protected String processFileUpload(String username, int version, String path, String filename, String file) throws JSONException {
		//
		return "";
	}

	//Members
	protected boolean			m_Running;
	protected ArrayList<Socket> m_Connections;
}
